import {
    ref,
    watch
} from "vue";
import {
    usemainStore
} from "@/stores/mainStore";
import {
    useRoute,
    useRouter,
    onBeforeRouteUpdate
} from "vue-router";
import {
    useCookies
} from '@vueuse/integrations/useCookies';

export function useTagList() {
    const mainStore = usemainStore();
    const route = useRoute();
    const currenPath = ref(route.path);
    const cookie = useCookies();
    watch(
        () => route.path,
        (newData) => {
            console.log(newData);
            currenPath.value = newData;
        }
    );
    const TagList = ref([{
        title: "后台首页",
        path: "/"
    }, ]);

    //添加路径的方法
    const addTabs = (tab) => {
        let noTab = TagList ?.value?.findIndex(t => t?.path == tab?.path) == -1;
        console.log(tab);
        if (noTab) {
            console.log("add");
            TagList.value.push(tab);
        }
        cookie.set("tagList", TagList?.value);
    }
    //监听路径
    onBeforeRouteUpdate((to, from) => {
        console.log("do");
        console.log(to, from);
        addTabs({
            title: to ?.meta?.title,
            path: to ?.path,
        })
    });

    //通过标签切换路径
    const router = useRouter();
    const tagClick = (path) => {
        router.push(path);
    };

    //使用cookie保存原来的状态
    function useCookie() {
        const cookieData = cookie.get("tagList");
        if (cookieData) TagList.value = cookieData;
    }
    useCookie();

    //关闭标签的功能
    const handleClose = (tag) => {
        if (tag.path !== '/') {
            //自动跳转到下一个页面或者上一个页面
            let index = TagList.value.findIndex(t => t === tag);
            if (index === TagList.value.length - 1) index--;
            else index++;
            console.log("index", index);
            const nextPath = TagList.value[index].path;
            router.push(nextPath);
            TagList.value = TagList.value.filter(t => t != tag);
            cookie.set("tagList", TagList?.value);

        }
    };

    //下拉框关闭操作
    const handleClear = (c) => {
        if (c === 'clearOther') {
            TagList.value = TagList.value.filter(t => t.path === '/' || t.path === currenPath.value);
        } else {
            TagList.value = TagList.value.filter(t => t.path === '/');
            currenPath.value = "/";
        }

        router.push(currenPath.value);
        cookie.set("tagList", TagList.value);
    }

    return{mainStore,currenPath,TagList,tagClick,handleClose,handleClear,addTabs}
}